package com.jiazaibendi.lottery.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jiazaibendi.lottery.dao.domain.UserInfo;
import com.jiazaibendi.lottery.service.RecordService;
import com.jiazaibendi.lottery.service.RedisService;
import com.jiazaibendi.lottery.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zy
 * @Date: 2021/8/9 19:24
 */
@Service
public class WxServiceImpl implements WxService {

    @Value("${weixin.appId}")
    public String appId;

    @Value("${weixin.appSecret}")
    public String appSecret;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RecordService recordService;

    @Override
    public UserInfo getOpenId(String code) {
//        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
        Map<String, Object> map = new HashMap<>();
        String jsonStr = restTemplate.getForObject(url, String.class, map);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr, JSONObject.class);
        if(jsonObject == null || jsonObject.getIntValue("errcode") != 0){
            throw new RuntimeException("获取用户token时出错");
        }
        String openid = jsonObject.getString("openid");
        if(StringUtils.isEmpty(openid)){
            throw new RuntimeException("获取用户openid时出错");
        }
        String token = jsonObject.getString("access_token");
        redisService.set("user_access_token",token,jsonObject.getLongValue("expires_in"));

        //获取用户信息
        JSONObject userInfo = getUserInfo(openid);
        //新增这个用户
        UserInfo user = recordService.getUserByOpenId(openid);
        if(user == null){
            user = new UserInfo();
            if(userInfo.getIntValue("subscribe") != 0){
                user.setHeadImage(userInfo.getString("headimgurl"));
                user.setNickname(userInfo.getString("nickname"));
            }
            user.setOpenid(openid);
            recordService.insertUser(user);
        }
        return user;
    }

    private JSONObject getUserInfo(String openid) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        Map<String, Object> map = new HashMap<>();
        String jsonStr = restTemplate.getForObject(url, String.class, map);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr, JSONObject.class);

        if(jsonObject == null || jsonObject.getIntValue("errcode") != 0){
            throw new RuntimeException("获取用户信息时出错");
        }
        return jsonObject;
    }

    private String getAccessToken() {
        String token = (String)redisService.get("wx_access_token");
        if (StringUtils.isEmpty(token)){
            //获取accessToken
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret=" + appSecret;
            Map<String, Object> map = new HashMap<>();
            String jsonStr = restTemplate.getForObject(url, String.class, map);
            JSONObject jsonObject = JSONObject.parseObject(jsonStr, JSONObject.class);
            if(jsonObject == null || jsonObject.getIntValue("errcode") != 0){
                throw new RuntimeException("获取用户token时出错");
            }
            token = jsonObject.getString("access_token");
            redisService.set("wx_access_token",token,jsonObject.getLongValue("expires_in"));
        }

        return token;
    }
}
